package io.renren.modules.app.api;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.*;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.entity.SmsLogVo;
import io.renren.modules.app.entity.UserVo;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.form.RegisterForm;
import io.renren.modules.app.service.ApiUserService;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 身份认证
 * @author zzh
 * @email 862583291@qq.com
 * @date 2018-12-25 17:27
 */
@Api("APP认证接口")
@RestController
@RequestMapping("/app/v1/auth")
public class ApiAuthController {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 发送短信验证码
     */
    @GetMapping("sendCode")
    @ApiOperation("发送短信验证码")
    public R sendCode(@RequestParam String phone, @RequestParam String type) throws UnsupportedEncodingException {
        if (StringUtil.isNullOrEmpty(phone)) {
            return R.error("手机号不能为空");
        }
        if (StringUtil.isNullOrEmpty(type)) {
            return R.error("参数不能为空");
        }
        if (type.equals("register")) {
            List<UserVo> users = userService.queryByMobile(phone);
            if (users != null && users.size() > 0) {
                return R.error("手机号码已被注册");
            }
        } else if (type.equals("findPassword")) {
            List<UserVo> users = userService.queryByMobile(phone);
            if (users != null) {
                if (users.size() == 0) {
                    return R.error("账户不存在");
                } else if (users.size() > 1) {
                    return R.error("账户异常");
                }
            } else {
                return R.error("账户不存在");
            }
        }
        // 一分钟之内不能重复发送短信
        //SmsLogVo smsLogVo = (SmsLogVo)J2CacheUtils.get("code" + phone);
        SmsLogVo smsLogVo = redisUtils.get("code" + phone, SmsLogVo.class);
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLogDate()) < 1 * 60) {
            return R.ok("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(6);
        String msgContent = "#code#=" + sms_code;
        String tpl_value = URLEncoder.encode(msgContent, "UTF-8");
        // 发送短信
        String result = null;
        String url = "http://v.juhe.cn/sms/send";
        Map params = new HashMap();
        params.put("mobile",phone);
        params.put("tpl_id","99648");
        params.put("tpl_value",tpl_value);
        params.put("key","545a0e9d4ab06f323b5a50f08d81a3a7");
        try {
            result = SmsUtil.net(url, params, "GET");
            JSONObject object = JSONObject.parseObject(result);
            if (object != null && Integer.parseInt(object.getString("error_code")) == 0) {
                smsLogVo = new SmsLogVo();
                smsLogVo.setLogDate(System.currentTimeMillis() / 1000);
                smsLogVo.setPhone(phone);
                smsLogVo.setSmsCode(sms_code);
                smsLogVo.setSmsText(msgContent);
                //J2CacheUtils.put("code" + phone + "", smsLogVo);
                redisUtils.set("code" + phone + "", smsLogVo);
                return R.ok("发送成功").put("data", sms_code);
            } else {
                return R.error("短信发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("短信发送失败");
        }
    }

    /**
     * 注册
     */
    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);

        List<UserVo> users = userService.queryByMobile(form.getMobile());
        if (users != null && users.size() > 0) {
            return R.error("手机号码已被注册");
        }
        SmsLogVo smsLogVo = redisUtils.get("code" + form.getMobile(), SmsLogVo.class);
        if (smsLogVo == null || !smsLogVo.getSmsCode().equals(form.getCode())) {
            return R.error("验证码有误");
        }
        UserVo user = new UserVo();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        userService.save(user);
        redisUtils.delete("code" + form.getMobile());
        return R.ok("注册成功");
    }

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
        long userId = userService.login(form);

        //生成token
        String token = jwtUtils.generateToken(userId);

        return R.ok().put("token",token).put("userId",userId);
    }

    /**
     * 找回密码
     */
    @ApiOperation("找回密码")
    @PostMapping("findPassword")
    public R findPassword(@RequestBody RegisterForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        List<UserVo> users = userService.queryByMobile(form.getMobile());
        Assert.isNull(users, "账户不存在");
        if (users.size() != 1) {
            return R.error("账户异常");
        }
        SmsLogVo smsLogVo = redisUtils.get("code" + form.getMobile(), SmsLogVo.class);
        if (smsLogVo == null || !smsLogVo.getSmsCode().equals(form.getCode())) {
            return R.error("验证码有误");
        }
        users.get(0).setPassword(DigestUtils.sha256Hex(form.getPassword()));
        userService.updateById(users.get(0));
        redisUtils.delete("code" + form.getMobile());
        return R.ok("密码修改成功");
    }

}
